package com.be.beadmin.design.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.ResultModel;
import com.be.beadmin.design.dto.input.ProductBomOverviewDto;
import com.be.beadmin.design.dto.input.StandProductBomOverviewPageDto;
import com.be.beadmin.design.dto.output.BomReviewExcelEx;
import com.be.beadmin.design.dto.output.BopEx;
import com.be.beadmin.design.dto.output.ProductBomOverviewEx;
import com.be.beadmin.design.entity.ProductBomOverview;
import com.be.beadmin.design.repository.ProductBomOverviewRepository;
import com.be.beadmin.design.service.ProductBomOverviewService;
import com.be.beadmin.service.impl.MinioService;
import com.google.common.io.ByteStreams;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zmy
 * @date 2023-02-16
 **/
@Api(tags = {"设计管理-Bom"})
@RestController
public class ProductBomOverviewController {

    @Autowired
    private ProductBomOverviewService productBomOverviewService;

    @Autowired
    private MinioService minioService;
    @Autowired
    private ProductBomOverviewRepository productBomOverviewRepository;

    @PostMapping(value = "/design/getProductBomOverviewByPage")
    public ResultModel getProductBomOverviewByPage(@RequestBody PageEntity pageEntity) {
        return ResultModel.success(productBomOverviewService.getProductBomOverviewByPage(pageEntity));
    }

    @ApiOperation("导出修改后和未修改的bom")
    @PostMapping(value = "/design/getProductBomOverviewAndReviewByPage")
    public ResultModel getProductBomOverviewAndReviewByPage(@RequestBody PageEntity pageEntity) {
        return ResultModel.success(productBomOverviewService.getProductBomOverviewAndReviewByPage(pageEntity));
    }

    @ApiOperation("获取某一个柜体的所有物料")
    @PostMapping(value = "/design/getProductBomOverviewByBatchProductId")
    public ResultModel getProductBomOverviewByBatchProductId(@RequestBody PageEntity pageEntity,
                                                             @ApiParam(value = "批次柜体id",required = true) @RequestParam String batchProductId,
                                                             HttpServletRequest request) {
        try {
            productBomOverviewService.getProductBomOverviewByBatchProductId(request,pageEntity,batchProductId);
        }catch (RuntimeException e){
            return ResultModel.error(110, e.getMessage());
        }
        return ResultModel.success();
    }

    @ApiOperation("获取标准柜体的所有物料")
    @PostMapping(value = "/design/getProductBomOverviewOfStandProduct")
    public ResultModel getProductBomOverviewOfStandProduct(@RequestBody StandProductBomOverviewPageDto standProductBomOverviewPageDto) {

        try {
            return ResultModel.success(productBomOverviewService.getProductBomOverviewOfStandProduct(standProductBomOverviewPageDto.getPageEntity(),standProductBomOverviewPageDto.getStandTypeId()));
        } catch (BeadminException e) {
            return ResultModel.error(-1,e.getMessage());
        } catch (Exception e) {
            return ResultModel.error(-2,e.getMessage());
        }


    }



    @ApiOperation("添加Bom，一种物料")
    @PostMapping("/design/addProductBomOverview")
    public ResultModel addProductBomOverview(@RequestBody ProductBomOverviewDto productBomOverviewDto) {
        productBomOverviewService.addProductBomOverview(productBomOverviewDto);
        return ResultModel.success(ResultModel.ADD);
    }

    @PostMapping("/design/delProductBomOverview")
    public ResultModel delProductBomOverview(@RequestBody ProductBomOverviewDto productBomOverviewDto) {
        productBomOverviewService.delProductBomOverview(productBomOverviewDto.getId());
        return ResultModel.success(ResultModel.DELETE);
    }

    @ApiOperation("更新Bom ")
    @PostMapping("/design/updateProductBomOverview")
    public ResultModel updateProductBomOverview(@RequestBody ProductBomOverviewDto productBomOverviewDto) {
        productBomOverviewService.updateProductBomOverview(productBomOverviewDto);
        return ResultModel.success(ResultModel.UPDATE);
    }


    @PostMapping("/design/exportProductBomOverview")
    public void exportProductBomOverview(HttpServletResponse response, @RequestBody PageEntity pageEntity) throws IOException {
        Page<ProductBomOverviewEx> productBomOverviewPage = productBomOverviewService.getProductBomOverviewByPage(pageEntity);
        List<ProductBomOverviewEx> productBomOverviewExes = productBomOverviewPage.getContent();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("ProductBomOverview接口", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xls");
        //EasyExcel.write(response.getOutputStream(), ProductBomOverviewEx.class).sheet("sheet1").doWrite(productBomOverviewExes);
        ExcelWriterBuilder excelWriterBuilder=EasyExcel.write(response.getOutputStream(), ProductBomOverviewEx.class);
        excelWriterBuilder.excelType(ExcelTypeEnum.XLS);
        excelWriterBuilder.sheet("sheet1").doWrite(productBomOverviewExes);
//    }
//    @ApiOperation("上传Bom")
//    @PostMapping("/design/uploadBom")
//    public ResultModel uploadBom(@RequestBody ProductBomOverviewDto productBomOverviewDto) throws Exception {
//
//
//        return ResultModel.success("成功上传Bom！");
//    }

//    @PostMapping("/design/addProductBomOverview")
//    public ResultModel addProductBomOverview(@ApiParam(value = "物料名称") @RequestParam String materialNam,
//                                             @ApiParam(value = "物料数量") @RequestParam String materialQty,
//                                             @ApiParam(value = "产品/柜体编号") @RequestParam String productId){
//
//        return ResultModel.success(ResultModel.ADD);
//    }
    }
    //上传Bom模板
    @PostMapping("/design/addBomByTemplate")
    public ResultModel addBomByTemplate(HttpServletRequest request,
                                        @ApiParam(value = "批次柜体id",required = true) @RequestParam String batchProductId,
                                        @ApiParam(value = "bom模板文件",required = true) @RequestParam("file") MultipartFile[] multipartFiles) throws IOException {
        try {
            for(MultipartFile multipartFile:multipartFiles) {
                productBomOverviewService.addBomByTemplate(request, batchProductId, multipartFile);
            }
        }catch (BeadminException e){

            return ResultModel.error(110, e.getMessage());
        }
        return ResultModel.success();
    }

    @ApiOperation("下载Bom模板")
    @PostMapping("/design/downloadBomTemplate")
    public void downloadProductDrawingInfo(HttpServletResponse response) throws Exception {

        //productDrawingInfoService.downloadProductDrawingInfo(id,drawingBucketName,response);
        try {

            //InputStream inputStream = fileInfoService.download(bucketName, id, response);
            String bomName = "Bom模板.xls";
            InputStream inputStream = minioService.downloadOne("beadmin", "Bom导入模板-20230607.xls");
            response.addHeader("Accept-Ranges", "bytes");
            response.addHeader("Content-disposition", "attachment;filename= "+bomName);
            response.addHeader("Content-Type", "text/plain;charset=utf-8");
            response.addHeader("Content-Length",String.valueOf(inputStream.available()));
            response.addHeader("Pragma","No-cache");
            response.addHeader("Cache-Control","No-cache");
            //response.addHeader("Content-Length",String.valueOf(inputStream));
            ServletOutputStream os = response.getOutputStream();

            ByteStreams.copy(inputStream, os);
            os.flush();
            //return  ResultModel.success("下载成功");
        } catch (Exception e) {
            //return ResultModel.error(99,"文件读取异常");
        }

    }
    @ApiOperation("确认上传")
    @PostMapping("/design/confirmUpdate")
    public ResultModel confirmUpdate(
            @ApiParam(value = "多行物料",required = true) @RequestParam List<ProductBomOverviewDto> productBomOverviewDtos) throws Exception {

        productBomOverviewService.confirmUpdate(productBomOverviewDtos);
        return  ResultModel.success("上传成功！");

    }
    @ApiOperation("bom变更")
    @PostMapping("/design/change")
    public ResultModel change(@ApiParam(value = "变更的数组id",required = true) @RequestParam List<String> ids,
                              @ApiParam(value = "变更的数组num",required = true) @RequestParam List<Integer> nums) throws IOException, ParseException {
        productBomOverviewService.change(ids,nums);
        return  ResultModel.success("提交审批成功！");
    }


    @ApiOperation("获取最大版本")
    @PostMapping("/design/getMax")
    public ResultModel getMax(@ApiParam(value = "柜体编码",required = true) @RequestParam String productCode) {
        List<ProductBomOverview> productBomOverviewsByProductCodeAndDelete = productBomOverviewRepository.findProductBomOverviewsByProductCodeAndDelete(productCode, 0);
        int max = 0;
        int max_second = 0;
        for (ProductBomOverview p:productBomOverviewsByProductCodeAndDelete) {
            max = Math.max(max, p.getVersion());
        }
        for (ProductBomOverview p:productBomOverviewsByProductCodeAndDelete) {
            if(max == p.getVersion()){
                max_second = Math.max(max_second, (p.getVersionSecond() == null ? 0 : p.getVersionSecond()));
            }
        }
        List<Integer> result = new ArrayList<>();
        result.add(max);
        result.add(max_second);
        return  ResultModel.success(result);
    }

    @ApiOperation("获取所有版本信息")
    @PostMapping("/design/getAllVersion")
    public ResultModel getAllVersion(@ApiParam(value = "柜体编码",required = true) @RequestParam String productCode) {
        List<ProductBomOverview> productBomOverviewsByProductCodeAndDelete = productBomOverviewRepository.findProductBomOverviewsByProductCodeAndDelete(productCode, 0);
        List<List<Integer>> result = new ArrayList<>();
        int index;
        for (ProductBomOverview p:productBomOverviewsByProductCodeAndDelete) {
            index = 0;
            for(List<Integer> t : result){
                if(t.get(0) == p.getVersion() && t.get(1) == (p.getVersionSecond() == null ? 0 : p.getVersionSecond())){
                    index = 1;
                    break;
                }
            }
            if(index != 1) {
                List<Integer> P_t = new ArrayList<>();
                P_t.add(p.getVersion());
                P_t.add(p.getVersionSecond() == null ? 0 : p.getVersionSecond());
                result.add(P_t);
            }
        }

        return  ResultModel.success(result);
    }
}
